package com.platform.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.platform.dao.AddressDao;
import com.platform.dao.CartDao;
import com.platform.dao.CommissionDao;
import com.platform.dao.GoodsDao;
import com.platform.dao.OrderDao;
import com.platform.dao.OrderGoodsDao;
import com.platform.dao.ProductDao;
import com.platform.dao.ShippingDao;
import com.platform.dao.UserDao;
import com.platform.entity.AddressEntity;
import com.platform.entity.CartEntity;
import com.platform.entity.CommissionEntity;
import com.platform.entity.GoodsEntity;
import com.platform.entity.GoodsReadPermissionEntity;
import com.platform.entity.OrderEntity;
import com.platform.entity.OrderGoodsEntity;
import com.platform.entity.ProductEntity;
import com.platform.entity.ShippingEntity;
import com.platform.entity.UserEntity;
import com.platform.util.CommonUtil;
import com.platform.utils.RRException;
import com.platform.utils.ResourceUtil;

/**
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-13 10:41:09
 */
@Service("orderService")
public class OrderService {
    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ShippingDao shippingDao;
	@Autowired
	private OrderGoodsDao orderGoodsDao;
	@Autowired
	private CartDao cartDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CommissionDao commissionDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private GoodsReadPermissionService goodsReadPermissionService;
    @Autowired
    private AddressDao addressDao;
    
    public OrderEntity queryObject(Integer id) {
        return queryObject(id,false);
    }

    public List<OrderEntity> queryList(Map<String, Object> map) {
        return queryList(map,false);
    }

    
    public OrderEntity queryObject(Integer id,Boolean isSetOrderGoods) {
    	OrderEntity order = orderDao.queryObject(id);
    	if(order != null && isSetOrderGoods) {
        	setOrderEntityOrderGoods(order);
    	}
        return order;
    }

    public List<OrderEntity> queryList(Map<String, Object> map,Boolean isSetOrderGoods) {
    	List<OrderEntity> orderList = orderDao.queryList(map);
    	if(isSetOrderGoods) {
    		for(OrderEntity order:orderList) {
            	setOrderEntityOrderGoods(order);
    		}
    	}
        return orderList;
    }
    
    private void setOrderEntityOrderGoods(OrderEntity order) {
    	List<OrderGoodsEntity> orderGoods = orderGoodsDao.queryListByOrderId(order.getId());
    	order.setOrderGoods(orderGoods);
    }

    public int queryTotal(Map<String, Object> map) {
        return orderDao.queryTotal(map);
    }

    public int save(OrderEntity order) {
        return orderDao.save(order);
    }

    public int update(OrderEntity order) {
        return orderDao.update(order);
    }

    public int cancel(Integer orderId,Integer userId) {
        return orderDao.cancel(orderId,userId);
    }
    public int confirm(Integer orderId,Integer userId) {
        return orderDao.confirm(orderId,userId);
    }
    
    public int paying(Integer orderId,Integer userId) {
        return orderDao.paying(orderId,userId);
    }
    
    public int deleteById(Integer orderId,Integer userId) {
        return orderDao.paying(orderId,userId);
    }
     
    public int delete(Integer id) {
        return orderDao.delete(id);
    }

    public int deleteBatch(Integer[] ids) {
        return orderDao.deleteBatch(ids);
    }

    public OrderEntity changeAddress(Integer id,Integer addressId) {
		OrderEntity orderInfo = queryObject(id,true);
		AddressEntity address = addressDao.queryObject(addressId);
		//收货地址和运费
		orderInfo.setConsignee(address.getUserName());
		orderInfo.setMobile(address.getTelNumber());
		orderInfo.setCountry(address.getNationalCode());
		orderInfo.setProvince(address.getProvinceName());	
		orderInfo.setCity(address.getCityName());
		orderInfo.setDistrict(address.getCountyName());
		orderInfo.setAddress(address.getDetailInfo());
		orderInfo.setAddressId(address.getId());
		orderDao.update(orderInfo);
		return orderInfo;
    }
    
    public int sendGoods(OrderEntity order) {
        Integer payStatus = order.getPayStatus();//付款状态
        if (2 != payStatus) {
            throw new RRException("此订单未付款！");
        }

        ShippingEntity shippingEntity = shippingDao.queryObject(order.getShippingId());
        if (null != shippingEntity) {
            order.setShippingName(shippingEntity.getName());
        }
        order.setOrderStatus(300);//订单已发货
        order.setShippingStatus(1);//已发货
        return orderDao.update(order);
    }
    
    @Transactional
    public OrderEntity newSaveByProduct(UserEntity user,AddressEntity addressVo,Integer productId,Integer productNum) {
        BigDecimal goodsTotalPrice= new BigDecimal(0.00);
        BigDecimal unitPrice= new BigDecimal(0.00);
        BigDecimal retailPrice= new BigDecimal(0.00);
        BigDecimal marketPrice= new BigDecimal(0.00);
        BigDecimal appExclusivePrice= new BigDecimal(0.00);
        BigDecimal counterPrice= new BigDecimal(0.00);
        ProductEntity product = productDao.queryObject(productId);
        GoodsEntity goods = goodsDao.queryObject(product.getGoodsId());
        		
        goodsTotalPrice = goodsTotalPrice.add(product.getSalePrice().multiply(new BigDecimal(productNum)));
        unitPrice = unitPrice.add(product.getUnitPrice().multiply(new BigDecimal(productNum)));
        retailPrice = retailPrice.add(product.getRetailPrice().multiply(new BigDecimal(productNum)));
        marketPrice = marketPrice.add(product.getMarketPrice().multiply(new BigDecimal(productNum)));
        appExclusivePrice = appExclusivePrice.add(product.getAppExclusivePrice().multiply(new BigDecimal(productNum)));
        counterPrice = counterPrice.add(product.getCounterPrice().multiply(new BigDecimal(productNum)));
        
    	OrderEntity orderInfo = new OrderEntity();
        orderInfo.setOrderGoodsName(goods.getName());
        orderInfo.setListPicUrl(goods.getListPicUrl());
    	orderInfo.setOrderSn(CommonUtil.generateOrderNumber());
        orderInfo.setUserId(user.getId());
//      AddressEntity addressVo = addressDao.queryObject(Integer.valueOf(map.get("selectAddressId").toString()));
        //收货地址和运费
        if(addressVo != null) {
        	orderInfo.setAddressId(addressVo.getId());
            orderInfo.setConsignee(addressVo.getUserName());
            orderInfo.setMobile(addressVo.getTelNumber());
            orderInfo.setCountry(addressVo.getNationalCode());
            orderInfo.setProvince(addressVo.getProvinceName());
            orderInfo.setCity(addressVo.getCityName());
            orderInfo.setDistrict(addressVo.getCountyName());
            orderInfo.setAddress(addressVo.getDetailInfo());
        }
        orderInfo.setAddTime(new Date());
        orderInfo.setGoodsPrice(goodsTotalPrice);
        orderInfo.setOrderPrice(goodsTotalPrice);
        orderInfo.setActualPrice(goodsTotalPrice);
        
        orderInfo.setUnitPrice(unitPrice);
        orderInfo.setRetailPrice(retailPrice);
        orderInfo.setMarketPrice(marketPrice);
        orderInfo.setAppExclusivePrice(appExclusivePrice);
        orderInfo.setCounterPrice(counterPrice);
        //快递费用
        orderInfo.setShippingId(0);
        orderInfo.setShippingFee(new BigDecimal(0));
        
        //积分抵扣金额
        orderInfo.setIntegral(0);
        orderInfo.setIntegralMoney(new BigDecimal(0));
        
        orderInfo.setOrderType("1");
        orderInfo.setOrderStatus(0);
        orderInfo.setShippingStatus(0);
        orderInfo.setPayStatus(0);
        orderInfo.setGoodsNumber(productNum);
        orderDao.save(orderInfo);
        //开启事务，插入订单信息和订单商品
        //统计商品总价
        List<OrderGoodsEntity> orderGoodsData = new ArrayList<OrderGoodsEntity>();
    	OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
        orderGoodsVo.setOrderId(orderInfo.getId());
        orderGoodsVo.setGoodsId(product.getGoodsId());
        orderGoodsVo.setProductId(productId);
        orderGoodsVo.setGoodsSn(product.getGoodsSn());
        orderGoodsVo.setGoodsName(goods.getName());
        orderGoodsVo.setListPicUrl(goods.getListPicUrl());
        orderGoodsVo.setMarketPrice(product.getCounterPrice()); //展示价格
        orderGoodsVo.setRetailPrice(product.getSalePrice());
        orderGoodsVo.setNumber(productNum);
        orderGoodsVo.setKeywords(product.getSpecificationValue());
        orderGoodsDao.save(orderGoodsVo);
        orderGoodsData.add(orderGoodsVo);
        orderInfo.setOrderGoods(orderGoodsData);
    	return orderInfo;
    }
    
    @Transactional
    public OrderEntity newSaveByCart(UserEntity user,Integer shopUserId,AddressEntity addressVo) {
        BigDecimal goodsTotalPrice= new BigDecimal(0.00);

        BigDecimal unitPrice= new BigDecimal(0.00);
        BigDecimal retailPrice= new BigDecimal(0.00);
        BigDecimal marketPrice= new BigDecimal(0.00);
        BigDecimal appExclusivePrice= new BigDecimal(0.00);
        BigDecimal counterPrice= new BigDecimal(0.00);
    	Map<String,Object> params = new HashMap<String,Object>();
    	params.clear();
    	params.put("userId", user.getId());
    	params.put("checked", 1);
    	List<CartEntity> checkedCarts = cartDao.queryList(params);
        StringBuffer buffer = new StringBuffer();
        String listPicUrl = null;
        int productNum = 0;
        for (CartEntity cartItem : checkedCarts) {
            goodsTotalPrice = goodsTotalPrice.add(cartItem.getSalePrice().multiply(new BigDecimal(cartItem.getNumber())));
            unitPrice = unitPrice.add(cartItem.getUnitPrice().multiply(new BigDecimal(cartItem.getNumber())));
            retailPrice = retailPrice.add(cartItem.getRetailPrice().multiply(new BigDecimal(cartItem.getNumber())));
            marketPrice = marketPrice.add(cartItem.getMarketPrice().multiply(new BigDecimal(cartItem.getNumber())));
            appExclusivePrice = appExclusivePrice.add(cartItem.getAppExclusivePrice().multiply(new BigDecimal(cartItem.getNumber())));
            counterPrice = counterPrice.add(cartItem.getCounterPrice().multiply(new BigDecimal(cartItem.getNumber())));
            productNum = productNum + cartItem.getNumber();
            if(listPicUrl == null) {
                listPicUrl = cartItem.getListPicUrl();
            }
            buffer.append(cartItem.getGoodsName());
        }
        
//        Float submitTotal = Float.valueOf(map.get("submit_total_price").toString());
//        if(Math.abs(goodsTotalPrice.floatValue()-submitTotal.floatValue())>=0.01) {
//        	throw new RRException("提交金额与购物车计算出来金额不一致！goodsTotalPrice:"+goodsTotalPrice.floatValue()+" submitTotal:"+submitTotal.floatValue(),99);
//        } 
        
    	OrderEntity orderInfo = new OrderEntity();
        orderInfo.setGoodsNumber(productNum);
        orderInfo.setOrderGoodsName(buffer.toString());
        orderInfo.setListPicUrl(listPicUrl);
    	orderInfo.setOrderSn(CommonUtil.generateOrderNumber());
        orderInfo.setUserId(user.getId());
        orderInfo.setShopUserId(shopUserId);
//      AddressEntity addressVo = addressDao.queryObject(Integer.valueOf(map.get("selectAddressId").toString()));
        //收货地址和运费
        if(addressVo != null) {
        	orderInfo.setAddressId(addressVo.getId());
            orderInfo.setConsignee(addressVo.getUserName());
            orderInfo.setMobile(addressVo.getTelNumber());
            orderInfo.setCountry(addressVo.getNationalCode());
            orderInfo.setProvince(addressVo.getProvinceName());
            orderInfo.setCity(addressVo.getCityName());
            orderInfo.setDistrict(addressVo.getCountyName());
            orderInfo.setAddress(addressVo.getDetailInfo());
        }
        //快递费
        //orderInfo.setFreightPrice(freightPrice);
        //留言
//        orderInfo.setPostscript(map.get("postscript").toString());
//        orderInfo.setPayName(map.get("pay_type").toString());
//        // 待付款
//    	if(map.get("pay_type").equals("balance") && user.getBalance().compareTo(submitTotal)>=0) {
//	        orderInfo.setOrderStatus(0);
//	        orderInfo.setShippingStatus(0);
//	        orderInfo.setPayStatus(2);
//	        orderInfo.setPayTime(new Date());
//	        userDao.payByBalance(user.getId(),submitTotal);
//			paySuccess(orderInfo);
//    	}
        
        //使用的优惠券
//        orderInfo.setCouponId(0);
//        orderInfo.setCouponPrice(0f);
        orderInfo.setAddTime(new Date());
        orderInfo.setGoodsPrice(goodsTotalPrice);
        orderInfo.setOrderPrice(goodsTotalPrice);
        orderInfo.setActualPrice(goodsTotalPrice);
        
        orderInfo.setCounterPrice(counterPrice);
        orderInfo.setUnitPrice(unitPrice);
        orderInfo.setRetailPrice(retailPrice);
        orderInfo.setMarketPrice(marketPrice);
        orderInfo.setAppExclusivePrice(appExclusivePrice);
        //快递费用
        orderInfo.setShippingId(0);
        orderInfo.setShippingFee(new BigDecimal(0));
        
        //积分抵扣金额
        orderInfo.setIntegral(0);
        orderInfo.setIntegralMoney(new BigDecimal(0));
        orderInfo.setOrderType("1");
        orderInfo.setOrderStatus(0);
        orderInfo.setShippingStatus(0);
        orderInfo.setPayStatus(0);
        orderDao.save(orderInfo);
        //开启事务，插入订单信息和订单商品
        //统计商品总价
        List<OrderGoodsEntity> orderGoodsData = new ArrayList<OrderGoodsEntity>();
        for (CartEntity goodsItem : checkedCarts) {
        	OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
            orderGoodsVo.setOrderId(orderInfo.getId());
            orderGoodsVo.setGoodsId(goodsItem.getGoodsId());
            orderGoodsVo.setGoodsSn(goodsItem.getGoodsSn());
            orderGoodsVo.setProductId(goodsItem.getProductId());
            orderGoodsVo.setGoodsName(goodsItem.getGoodsName());
            orderGoodsVo.setListPicUrl(goodsItem.getListPicUrl());
            orderGoodsVo.setMarketPrice(goodsItem.getCounterPrice());
            orderGoodsVo.setRetailPrice(goodsItem.getSalePrice());
            orderGoodsVo.setNumber(goodsItem.getNumber());
            orderGoodsVo.setKeywords(goodsItem.getKeywords());
            orderGoodsDao.save(orderGoodsVo);
            orderGoodsData.add(orderGoodsVo);
        }
        orderInfo.setOrderGoods(orderGoodsData);
        //清空已购买的商品
    	params.clear();
    	params.put("userId", user.getId());
    	cartDao.deleteBuyCart(params);
    	return orderInfo;
    }
    
    @Transactional
    public OrderEntity newSaveByGoods(UserEntity user,Integer shopUserId,AddressEntity addressVo,Integer goodsId,Integer goodsNum,String orderType) {
        BigDecimal goodsTotalPrice= new BigDecimal(0.00);
        BigDecimal unitPrice= new BigDecimal(0.00);
        BigDecimal retailPrice= new BigDecimal(0.00);
        BigDecimal marketPrice= new BigDecimal(0.00);
        BigDecimal appExclusivePrice= new BigDecimal(0.00);
        BigDecimal counterPrice= new BigDecimal(0.00);
        
        GoodsEntity goods = goodsDao.queryObject(goodsId);
        		
        goodsTotalPrice = goodsTotalPrice.add(goods.getSalePrice(user).multiply(new BigDecimal(goodsNum)));
        unitPrice = unitPrice.add(goods.getUnitPrice().multiply(new BigDecimal(goodsNum)));
        retailPrice = retailPrice.add(goods.getRetailPrice().multiply(new BigDecimal(goodsNum)));
        marketPrice = marketPrice.add(goods.getMarketPrice().multiply(new BigDecimal(goodsNum)));
        appExclusivePrice = appExclusivePrice.add(goods.getAppExclusivePrice().multiply(new BigDecimal(goodsNum)));
        counterPrice = counterPrice.add(goods.getCounterPrice().multiply(new BigDecimal(goodsNum)));
    	OrderEntity orderInfo = new OrderEntity();
    	orderInfo.setGoodsNumber(goodsNum);
    	orderInfo.setOrderGoodsName(goods.getName());
        orderInfo.setListPicUrl(goods.getListPicUrl());
    	orderInfo.setOrderSn(CommonUtil.generateOrderNumber());
        orderInfo.setUserId(user.getId());
        orderInfo.setShopUserId(shopUserId);
//      AddressEntity addressVo = addressDao.queryObject(Integer.valueOf(map.get("selectAddressId").toString()));
        //收货地址和运费
        if(addressVo != null) {
        	orderInfo.setAddressId(addressVo.getId());
            orderInfo.setConsignee(addressVo.getUserName());
            orderInfo.setMobile(addressVo.getTelNumber());
            orderInfo.setCountry(addressVo.getNationalCode());
            orderInfo.setProvince(addressVo.getProvinceName());
            orderInfo.setCity(addressVo.getCityName());
            orderInfo.setDistrict(addressVo.getCountyName());
            orderInfo.setAddress(addressVo.getDetailInfo());
        }
        orderInfo.setAddTime(new Date());
        orderInfo.setGoodsPrice(goodsTotalPrice);
        orderInfo.setOrderPrice(goodsTotalPrice);
        orderInfo.setActualPrice(goodsTotalPrice);
        
        orderInfo.setCounterPrice(counterPrice);
        orderInfo.setUnitPrice(unitPrice);
        orderInfo.setRetailPrice(retailPrice);
        orderInfo.setMarketPrice(marketPrice);
        orderInfo.setAppExclusivePrice(appExclusivePrice);
        //快递费用
        orderInfo.setShippingId(0);
        orderInfo.setShippingFee(new BigDecimal(0));
        
        //积分抵扣金额
        orderInfo.setIntegral(0);
        orderInfo.setIntegralMoney(new BigDecimal(0));
        
        orderInfo.setOrderType(orderType);
        orderInfo.setOrderStatus(0);
        orderInfo.setShippingStatus(0);
        orderInfo.setPayStatus(0);
        orderDao.save(orderInfo);
        //开启事务，插入订单信息和订单商品
        //统计商品总价
        List<OrderGoodsEntity> orderGoodsData = new ArrayList<OrderGoodsEntity>();
    	OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
        orderGoodsVo.setOrderId(orderInfo.getId());
        orderGoodsVo.setGoodsId(goods.getId());
        orderGoodsVo.setGoodsSn(goods.getGoodsSn());
        orderGoodsVo.setGoodsName(goods.getName());
        orderGoodsVo.setListPicUrl(goods.getListPicUrl());
        orderGoodsVo.setMarketPrice(goods.getCounterPrice());
        orderGoodsVo.setRetailPrice(goods.getSalePrice(user));
        orderGoodsVo.setNumber(goodsNum);
        orderGoodsVo.setKeywords(goods.getKeywords());
        orderGoodsDao.save(orderGoodsVo);
        orderGoodsData.add(orderGoodsVo);
        orderInfo.setOrderGoods(orderGoodsData);
    	return orderInfo;
    }

    @Transactional
    public void payOrderByBalance(OrderEntity orderInfo,UserEntity user) {
    	if(user.getBalance().compareTo(orderInfo.getActualPrice().floatValue())>=0) {
//	        orderInfo.setOrderStatus(201);
//	        orderInfo.setShippingStatus(0);
//	        orderInfo.setPayStatus(2);
//	        orderInfo.setPayTime(new Date());
    		orderInfo.setPayName("balance");
	        userDao.payByBalance(user.getId(),orderInfo.getActualPrice().floatValue());
			paySuccess(orderInfo);
    	}else {
            throw new RRException("余额不足，请充值后再付款！");
    	}
    }

    @Transactional
    public void payNotify(WxPayOrderNotifyResult notifyResult) {
    	OrderEntity order = orderDao.queryObject(notifyResult.getOutTradeNo());
    	String tradeNo = notifyResult.getTransactionId();
    	order.setTradeNo(tradeNo);
        if ("SUCCESS".equals(notifyResult.getResultCode())) {
        	order.setPayId(notifyResult.getTransactionId());
        	order.setPayName("wx");
			paySuccess(order);
        } else {
			order.setOrderStatus(103);
			order.setPayStatus(3);
			order.setPayTime(new Date());
			order.setPayFailMsg(notifyResult.getResultCode() + "   "+ notifyResult.getErrCodeDes());
			orderDao.update(order);
        }
    }

    
    private void paySuccess(OrderEntity order) {
    	if(order.getOrderStatus() != 0) {
    		throw new RRException("订单重复付款，请核查或联系管理员！");
    	}
    	if(order.getOrderType().equals("5") || order.getOrderType().equals("6")) {
    		order.setOrderStatus(301);
    	}else if(order.getOrderType().equals("7")){
    		order.setOrderStatus(301);
    	}else {
    		order.setOrderStatus(201);
    	}
		order.setPayStatus(2);
		order.setShippingStatus(0);
		order.setPayTime(new Date());
		if(order.getId()==null)
			orderDao.save(order);
		else
			orderDao.update(order);
		
		//支付成功 未绑定的绑定上级
		UserEntity buyUser = userDao.queryObject(order.getUserId());
		if((buyUser.getParentId() == null || buyUser.getParentId() == 0) && order.getShopUserId() !=0) {
			buyUser.setParentId(order.getShopUserId());
		}
		
		if(order.getOrderType().equals("5")) {
			//单次充值>3000升级会员
			if(buyUser.getUserLevelId() == 0 && order.getOrderPrice().floatValue()>=3000) {
				buyUser.setUserLevelId(1);
			}
			buyUser.addBalance(order.getGoodsPrice().floatValue());
		}else if(order.getOrderType().equals("6")) {//成为代理
			buyUser.addBalance(order.getGoodsPrice().floatValue());
			buyUser.addDeposit(order.getDepositPrice().floatValue()); //押金
			buyUser.setUserLevelId(buyUser.getUserLevelId() + 1);
		}else if(order.getOrderType().equals("7") || order.getOrderType().equals("8")) {
			GoodsReadPermissionEntity goodsReadPermission = new GoodsReadPermissionEntity();
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("orderId", order.getId());
			List<OrderGoodsEntity> orderGoodsList = orderGoodsDao.queryList(params);
			for(OrderGoodsEntity orderGoods:orderGoodsList) {
				goodsReadPermission.setGoodsId(orderGoods.getGoodsId());
				goodsReadPermission.setOrderId(order.getId());
				goodsReadPermission.setSource(1);
				goodsReadPermission.setUserId(order.getUserId());
				goodsReadPermissionService.save(goodsReadPermission);
			}
		}else if(order.getOrderType().equals("9")) {
			GoodsReadPermissionEntity goodsReadPermission = new GoodsReadPermissionEntity();
			goodsReadPermission.setGoodsId(-1);
			goodsReadPermission.setOrderId(order.getId());
			goodsReadPermission.setSource(1);
			goodsReadPermission.setUserId(order.getUserId());
			goodsReadPermissionService.save(goodsReadPermission);
		}
		//TODO 会员积分等是否增加
		userDao.update(buyUser);
		if(order.getOrderType().equals("1")) {
			UserEntity agentUser = userDao.queryObject(buyUser.getParentId());
			//TODO  实际支付金额  还是 订单总价（包含优惠券金额）
			commission(order,agentUser,order.getActualPrice(),buyUser);    
		} 
	}
    
    private void commission(OrderEntity order,UserEntity parentUser,BigDecimal nowPrice,UserEntity buyUser) {
    	if(parentUser.getId() == 0 || parentUser.getId().equals(buyUser.getId())) {
    		return;
    	}
    	BigDecimal parentPrice = order.getSalePriceByLevel(parentUser.getUserLevelId());
    	if(parentPrice.compareTo(nowPrice)<0) {
    		Float  tmp = nowPrice.subtract(parentPrice).floatValue();
    		CommissionEntity commission = new CommissionEntity();
    		commission.setCreateDate(new Date());
    		commission.setIncome(tmp);
    		commission.setIncomeType(Integer.valueOf(order.getOrderType()));
    		commission.setIncomeUserId(parentUser.getId());
    		commission.setOrderId(order.getId());
    		commission.setUserId(order.getUserId());
    		commission.setGoodsName(order.getOrderGoodsName());
    		commission.setListPicUrl(order.getListPicUrl());
    		commission.setBuyUserName(buyUser.getNickname());
    		commissionDao.save(commission);
    		userDao.addRecharge(parentUser.getId(), tmp);
    	}
    	
    	commission(order,userDao.queryObject(parentUser.getParentId()),parentPrice,buyUser);
    }
    
    public OrderEntity recharge(Map<String, Object> map,UserEntity user,Integer shopUserId) {
    	OrderEntity orderInfo = new OrderEntity();
    	BigDecimal recharge;
    	if(map.get("recharge") != null) {
            recharge= new BigDecimal(map.get("recharge").toString());
    	}else {
            recharge= new BigDecimal(3000);
    	}
        orderInfo.setOrderGoodsName("账号余额充值" + recharge + "元");
        orderInfo.setListPicUrl(ResourceUtil.getConfigByName("logo.url"));
    	orderInfo.setOrderSn(CommonUtil.generateOrderNumber());
        orderInfo.setUserId(user.getId());
        orderInfo.setAddTime(new Date());
        orderInfo.setOrderPrice(recharge);
        orderInfo.setGoodsPrice(recharge);
        orderInfo.setActualPrice(recharge);
        orderInfo.setOrderStatus(0);
        orderInfo.setPayStatus(0);
        orderInfo.setOrderType("5");
        orderInfo.setShopUserId(shopUserId);
        orderDao.save(orderInfo);
        return orderInfo;
    }
    
    public OrderEntity toForeverVip(UserEntity user) {
    	OrderEntity orderInfo = new OrderEntity();
    	BigDecimal recharge;
    	BigDecimal total;
        recharge = new BigDecimal(999);
        total = new BigDecimal(999);
        orderInfo.setOrderGoodsName("终身会员");
        orderInfo.setListPicUrl(ResourceUtil.getConfigByName("logo.url"));
    	orderInfo.setOrderSn(CommonUtil.generateOrderNumber());
        orderInfo.setUserId(user.getId());
        orderInfo.setAddTime(new Date());
        orderInfo.setOrderPrice(total);
        orderInfo.setGoodsPrice(recharge);
        orderInfo.setDepositPrice(new BigDecimal(0));
        orderInfo.setActualPrice(total);
        orderInfo.setOrderStatus(0);
        orderInfo.setPayStatus(0);
        orderInfo.setOrderType("8");
        orderDao.save(orderInfo);
        return orderInfo;
    }

    public OrderEntity upgrade(UserEntity user) {
    	//历史  升级类的订单取消
    	orderDao.cancelUpgradeOrder(user.getId());
    	
    	OrderEntity orderInfo = new OrderEntity();
    	BigDecimal recharge;
    	BigDecimal deposit;
    	BigDecimal total;
    	if(user.getUserLevelId() == 1) {
            recharge = new BigDecimal(10000);
            deposit = new BigDecimal(2000);
            total = new BigDecimal(12000);
            orderInfo.setOrderGoodsName("升级至代理，其中充值" + recharge + "元,押金"+deposit+"元");
    	}else if(user.getUserLevelId() == 2){
            recharge = new BigDecimal(20000);
            deposit = new BigDecimal(3000);
            total = new BigDecimal(23000);
            orderInfo.setOrderGoodsName("升级至总代，其中余额充值" + recharge + "元,押金"+deposit+"元");
    	}else if(user.getUserLevelId() == 0){
            recharge = new BigDecimal(3000);
            deposit = new BigDecimal(0);
            total = new BigDecimal(3000);
            orderInfo.setOrderGoodsName("升级至VIP，其中余额充值" + recharge + "元");
    	}else {
    		return null;
    	}
        orderInfo.setListPicUrl(ResourceUtil.getConfigByName("logo.url"));
    	orderInfo.setOrderSn(CommonUtil.generateOrderNumber());
        orderInfo.setUserId(user.getId());
        orderInfo.setAddTime(new Date());
        orderInfo.setOrderPrice(total);
        orderInfo.setGoodsPrice(recharge);
        orderInfo.setDepositPrice(deposit);
        orderInfo.setActualPrice(total);
        orderInfo.setOrderStatus(0);
        orderInfo.setPayStatus(0);
        orderInfo.setOrderType("6");
        orderDao.save(orderInfo);
        return orderInfo;
    }
    
    public int updateRemark(Integer orderId,String remark,Integer userId) {
    	return orderDao.updateRemark(orderId,remark,userId);
    }
    
    /**
     * 定时取消 3小时未支付的工单
     */
    public void cancelNoPayOrder() {
    	logger.info("=================start run OrderService cancelNoPayOrder=======================");
    	
    	orderDao.cancelNoPayOrder();
    	
    }
}
